//
//  MYGPageTableView.swift
//  MYGrow
//
//  Created by 林矗 on 2024/3/16.
//

import UIKit
import MJRefresh

class MYGPageTableView: UITableView {
    // MARK: - Property
    var loadDataAction: ((Bool) -> ())?
    
    // MARK: - init
    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
        configUI()
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func reloadData() {
        super.reloadData()
        self.mj_footer?.isHidden = self.visibleCells.count == 0
    }
    
    
    // MARK: - UI
    private func configUI() {
        self.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.loadDataAction?(true)
        })
        
        self.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.loadDataAction?(false)
        })
        
        self.mj_footer?.isHidden = true
    }
    
    public func endRefreshing(noMoreData: Bool) {
        self.mj_header?.endRefreshing()
        if noMoreData {
            self.mj_footer?.endRefreshingWithNoMoreData()
        } else {
            self.mj_footer?.endRefreshing()
        }
    }
    
    public func beginRefreshing() {
        if self.mj_header!.isRefreshing {
            loadDataAction?(true)
        } else {
            self.mj_header?.beginRefreshing()
        }
    }
}
